package Java_Concurrency_in_Practice.c7_2_1;

import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;

/**
 * 不支持关闭的生产者 - 消费者 日志服务
 */
public class LogWriter {
    private final BlockingQueue<String> queue;
    private final LoggerThread logger;

    public LogWriter(BlockingQueue<String> queue, LoggerThread logger) {
        this.queue = queue;
        this.logger = logger;
    }

    public void log(String msg) throws InterruptedException {
        queue.put(msg);
    }

    public void start() {
        logger.start();
    }

    private class LoggerThread extends Thread {
        private final PrintWriter writer = null;

        @Override
        public void run() {
            try {
                while (true)
                    writer.println(queue.take());
            } catch (InterruptedException ignore) {
            } finally {
                writer.close();
            }
        }
    }
}
